package com.hxd.otc.module.my.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionLazyFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.BankType;
import com.hxd.otc.dialog.ForbiddenBankCardDialog;
import com.hxd.otc.dialog.PhotoDialog;
import com.hxd.otc.module.my.activity.BankAeraChooseActivity;
import com.hxd.otc.module.my.activity.SecurityCenterActivity;
import com.hxd.otc.module.my.contract.AddAlipayOrWeiXinContract;
import com.hxd.otc.module.my.presenter.AddAlipayOrWeiXinPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.AddressUtil;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.DateUtil;
import com.hxd.otc.utils.FileUtils;
import com.hxd.otc.utils.LubanUtils;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.UCropUtils;
import com.hxd.otc.widget.BlocksToast;
import com.hxd.otc.widget.EditInfoInputView;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.yalantis.ucrop.UCrop;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Created by lzy on 2018/6/8 0008.
 * description ${添加支付宝}
 */
public class AddAlipayOrWeiXinFragment extends PermissionLazyFragment<AddAlipayOrWeiXinPresenter> implements AddAlipayOrWeiXinContract.View {
    @BindView(R.id.editInfoInputView_name)
    EditInfoInputView mEditInfoInputViewName;
    @BindView(R.id.editInfoInputView_account)
    EditInfoInputView mEditInfoInputViewAccount;
    @BindView(R.id.editInfoInputView_for_note)
    EditInfoInputView mEditInfoInputViewForNote;
    @BindView(R.id.tv_confirm)
    TextView mTvConfirm;
    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R.id.tv_choose_area)
    TextView tvChooseArea;
    @BindView(R.id.fl_add_qr_code)
    FrameLayout mFlAddQrCode;
    @BindView(R.id.tv_reminder)
    TextView mTvReminder;
    @BindView(R.id.tv_add_qr_code)
    TextView mTvAddQrCode;
    @BindView(R.id.tv_hint)
    TextView tvHint;

    private static final int PICK_IMAGE_REQUEST_CODE = 100;
    private static final int OPEN_CAMERA_REQUEST_CODE = 101;
    public static final int REQUEST_CODE_AREA = 123;//地区选择
    boolean isWeixin;
    public static final String EXTRA_BANK_TYPE = "bank_type";
    private ForbiddenBankCardDialog<String> mGoToSetExValidDialog;


    @Override
    protected void initView() {
        Bundle bundle = getArguments();
        BankType bankType = (BankType) bundle.getSerializable(EXTRA_BANK_TYPE);
        if (bankType == null) bankType = BankType.ALIPAY;//默认支付宝
        mPresenter.setBankType(bankType);

        isWeixin = BankType.WEXIN.getType() == bankType.getType();
        mTvReminder.setText(isWeixin ? R.string.my_add_weixin_reminder : R.string.my_add_alipay_reminder);
        mEditInfoInputViewName.setLabelText(getString(isWeixin ? R.string.my_nickname : R.string.my_add_pay_name));
        mEditInfoInputViewName.setInputHint(getString(isWeixin ? R.string.my_please_enter_your_weixin_nickname : R.string.my_please_enter_your_alipay_name));
        mEditInfoInputViewAccount.setInputHint(getString(isWeixin ? R.string.my_please_enter_your_weixin_account : R.string.my_please_enter_your_alipay_account));
        tvHint.setText(isWeixin ? getString(R.string.add_weichat_tips) : getString(R.string.add_alipay_tips));
    }

    @Override
    protected void initData() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_add_alipay;
    }

    @Override
    protected AddAlipayOrWeiXinPresenter createPresenter() {
        return new AddAlipayOrWeiXinPresenter(this);
    }

    public static AddAlipayOrWeiXinFragment getInstance(BankType bankType) {
        AddAlipayOrWeiXinFragment addAlipayOrWeiXinFragment = new AddAlipayOrWeiXinFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_BANK_TYPE, bankType);
        addAlipayOrWeiXinFragment.setArguments(bundle);
        return addAlipayOrWeiXinFragment;
    }


    @Override
    protected void initEvent() {
    }


    @OnClick({R.id.tv_confirm, R.id.fl_add_qr_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_confirm:
                onConfirm();
                break;
            case R.id.fl_add_qr_code:
                showPhotoDialog();
                break;
        }

    }

    private void onConfirm() {
        if (TextUtils.isEmpty(tvChooseArea.getText().toString())) {
            showToast(getString(R.string.choose_country_or_region));
            return;
        }
        String name = mEditInfoInputViewName.getText();
        if (TextUtils.isEmpty(name)) {
            showToast(mEditInfoInputViewName.getHint());
            return;
        }
        String account = mEditInfoInputViewAccount.getText();
        if (TextUtils.isEmpty(account)) {
            showToast(mEditInfoInputViewAccount.getHint());
            return;
        }

        if (!UserHelper.isSetExValidType()) {
            showGotoSetExValidDialog();
            return;
        }

        if (outImageUri == null) {
            showToast(getString(R.string.my_please_upload_the_qr_code_of_payment_collection));
            return;
        }

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                viewSaveToImage(outImageUri);
            }
        });

//        mPresenter.addAliPay(account, mAddress, tvChooseArea.getText().toString().trim(), name, remark);
    }

    private void showGotoSetExValidDialog() {
        if (mGoToSetExValidDialog == null)
            mGoToSetExValidDialog = new ForbiddenBankCardDialog<>(getContext());
        mGoToSetExValidDialog.dismiss();
        mGoToSetExValidDialog
                .setMessage(ResourceUtil.getString(R.string.your_are_not_set_ex_valid_mode_should_go_to_security_center_set))
                .setData("")
                .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                    @Override
                    public void onConfirm(String data) {
                        $startActivity(SecurityCenterActivity.class);
                    }
                }).show();
    }

    @OnClick(R.id.cl_choose_area)
    public void onClickArea() {
        $startActivityForResult(BankAeraChooseActivity.class, REQUEST_CODE_AREA, false);
    }

    private PhotoDialog mPhotoDialog;
    private File mCameraFile;
    private Uri mCameraUri;

    protected void showPhotoDialog() {
        if (mPhotoDialog == null) {
            mPhotoDialog = new PhotoDialog(getActivity());
        }
        if (!mPhotoDialog.isShowing()) {
            mPhotoDialog.show();
        }
        mPhotoDialog.setOnPhotoDialogItemClickListener(new PhotoDialog.OnPhotoDialogItemClickListener() {
            @Override
            public void onClickCamera(View view) {
                mPhotoDialog.dismiss();
                openCamera();
            }

            @Override
            public void onClickAlbum(View view) {
                mPhotoDialog.dismiss();
                openAlbum(1);
            }

            @Override
            public void onClickFee(View view) {

            }

            @Override
            public void onClickCancel(View view) {
                mPhotoDialog.dismiss();
            }
        });
    }

    protected void openCamera() {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                onCamera();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                BlocksToast.get().showToast(R.string.camera_permissions_are_required);
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                showForbidPermissionDialog();
            }

            @Override
            public void onLowVersion() {
                onCamera();
            }
        }, Manifest.permission.CAMERA);
    }

    private void onCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (cameraIntent.resolveActivity(getContext().getPackageManager()) != null) {
            mCameraFile = FileUtils.outImageFile(getContext(), FileUtils.CAMERA);
            mCameraUri = FileUtils.fileToUri(getContext(), mCameraFile, cameraIntent);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraUri);
            startActivityForResult(cameraIntent, OPEN_CAMERA_REQUEST_CODE);
        }
    }


    protected void openAlbum(int maxImage) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(maxImage)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(PICK_IMAGE_REQUEST_CODE);
    }

    @Override
    public void addAliPayOrWeiXinSuccess(BankType mBankType, String msg) {
        dismissSpinnerDlg();
        showToast(msg);
        getActivity().setResult(Activity.RESULT_OK);
        getActivity().finish();
    }

    Uri outImageUri;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        //拍照返回结果
        if (requestCode == OPEN_CAMERA_REQUEST_CODE) {
            if (FileUtils.isImageFile(mCameraFile)) {
                UCropUtils.cropImageByFragment(mCameraUri, Uri.fromFile(FileUtils.outImageFile(getActivity(), FileUtils.CAMERA)), 1, 1
                        , DataUtils.dp2px(getActivity(), 200), DataUtils.dp2px(getActivity(), 200), this);
//                resultFiles(mCameraFile);
            }
            //裁剪图片返回结果
        } else if (requestCode == UCrop.REQUEST_CROP) {
            outImageUri = UCrop.getOutput(data);
            if (outImageUri != null) {
                mFlAddQrCode.setEnabled(false);
                mIvQrCode.setVisibility(View.VISIBLE);
                mTvAddQrCode.setVisibility(View.GONE);
                mIvQrCode.setImageURI(outImageUri);
            }
            //相册返回
        } else if (requestCode == PICK_IMAGE_REQUEST_CODE) {
            List<String> filePaths = Matisse.obtainPathResult(data);
            if (filePaths != null && filePaths.size() > 0) {
                UCropUtils.cropImageByFragment(FileUtils.fileToUri(getActivity()
                        , new File(filePaths.get(0))), Uri.fromFile(FileUtils.outImageFile(getActivity(), FileUtils.CAMERA)), 1, 1
                        , DataUtils.dp2px(getActivity(), 200), DataUtils.dp2px(getActivity(), 200), this);
//                resultFiles(new File(filePaths.get(0)));
            }
        } else if (requestCode == REQUEST_CODE_AREA) {
            tvChooseArea.setText(data.getStringExtra(BankAeraChooseActivity.RESULT_EXTRA_AERA));
        }
    }

    private void resultFiles(@NonNull File file) {
        mFlAddQrCode.setEnabled(false);
        mIvQrCode.setVisibility(View.VISIBLE);
        mTvAddQrCode.setVisibility(View.GONE);
        LubanUtils lubanUtils = new LubanUtils();
        ArrayList<String> list = new ArrayList<>();
        list.add(file.getAbsolutePath());
        lubanUtils.withRx(getActivity(), list, new Consumer<List<File>>() {
            @Override
            public void accept(List<File> files) throws Exception {
                mPresenter.uploadImage(files.get(0));
                showSpinnerDlg(getString(R.string.be_uploading), false);
            }
        });
    }

    @Override
    public void uploadImageSuccess(String imageId) {

//        String imageUrl = UIUtils.getServiceImageUrlByPath(imageId);
//        LogUtils.e("imageUrl:" + imageUrl);
//        GlideUtils.loadCenterCrop(AddAlipayOrWeiXinFragment.this, imageUrl, mIvQrCode, R.mipmap.icon_add_qr_code);

        mFlAddQrCode.setEnabled(true);
        dismissSpinnerDlg();
//        showToast(getString(R.string.upload_image_success));
        mPresenter.addAliPay(mEditInfoInputViewAccount.getText(), imageId, tvChooseArea.getText().toString().trim(),
                mEditInfoInputViewName.getText(), mEditInfoInputViewForNote.getText());
    }

    @Override
    public void uploadImageFail(String errMessage) {
        mIvQrCode.setVisibility(View.GONE);
        mTvAddQrCode.setVisibility(View.VISIBLE);
        mFlAddQrCode.setEnabled(true);
        dismissSpinnerDlg();
        showToast(getString(R.string.upload_fail));
    }

    Bitmap saveBitmap = null;

    /**
     * 保存二维码图片
     */
    private Bitmap createSaveQRBitmap(Uri uri) {
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int height = metric.heightPixels;   // 屏幕高度（像素）
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_bank_qr_code, null, false);
        // 整个View的大小 参数是左上角 和右下角的坐标
        view.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(DensityUtil.dp2px(550), View.MeasureSpec.AT_MOST);
        /** 当然，measure完后，并不会实际改变View的尺寸，需要调用View.layout方法去进行布局。
         * 按示例调用layout函数后，View的大小将会变成你想要设置成的大小。
         */
        view.measure(measuredWidth, measuredHeight);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        ImageView qr = view.findViewById(R.id.iv_save_qr_address);
        TextView tvHint = view.findViewById(R.id.tv_hint);

        ImageView ivTitle = view.findViewById(R.id.iv_title);
        LinearLayout llContent = view.findViewById(R.id.ll_content);

        ivTitle.setImageResource(isWeixin ? R.mipmap.weixinzhifu : R.mipmap.zhifubao);
        llContent.setBackgroundColor(isWeixin ? Color.parseColor("#519761") : Color.parseColor("#417FDB"));

        tvHint.setText(isWeixin ? getString(R.string.wechat_sweep_payment) : getString(R.string.zhifubao_sweep_payment));

//        qr.setImageBitmap(qrBitmap);
        qr.setImageURI(uri);
        TextView tv_name = view.findViewById(R.id.tv_save_qr_user_name);
        TextView tv_pay_name = view.findViewById(R.id.tv_pay_name);
        tv_pay_name.setText(isWeixin ? getString(R.string.weixin_pay_name) : getString(R.string.zhifubao_pay_name));
        tv_name.setText(mEditInfoInputViewName.getText().toString());

        return loadBitmapFromView(view);
    }

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

    private void viewSaveToImage(Uri uri) {
        if (saveBitmap != null && !saveBitmap.isRecycled()) {
            saveBitmap.recycle();
            saveBitmap = null;

        }
        saveBitmap = createSaveQRBitmap(uri);
        if (saveBitmap != null) {
            onShowLoading();
            AddressUtil.saveAddress(saveBitmap, getString(R.string.alipay_qrcode) + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"),
                    new AddressUtil.SaveAddressListener() {
                        @Override
                        public void fail(String str) {
                            onHideLoading();
                            showToast(str);
                        }

                        @Override
                        public void success(String str) {
                            onHideLoading();
                            resultFiles(new File(str));
                        }
                    });
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (saveBitmap != null && !saveBitmap.isRecycled()) {
            saveBitmap.recycle();
            saveBitmap = null;
        }
    }

}
